package cloud.xiguapi.ubas.analysis.hotitems;

import cloud.xiguapi.ubas.analysis.hotitems.model.*;
import cloud.xiguapi.ubas.model.HotItemsViewCount;
import cloud.xiguapi.ubas.model.UserBehavior;
import cloud.xiguapi.ubas.utils.JacksonUtils;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

import static cloud.xiguapi.ubas.constant.JobNameConstant.KAFKA_HOT_ITEMS;

/**
 * 流式数据热门商品统计
 *
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-18 下午 05:08
 * desc:
 */
@Component
public class KafkaHotItemsAnalysis {

    private final StreamExecutionEnvironment env;

    private final Properties kafkaProperties;

    @Autowired
    public KafkaHotItemsAnalysis(StreamExecutionEnvironment env, Properties kafkaProperties) {
        this.env = env;
        this.kafkaProperties = kafkaProperties;
    }

    @Async("kafkaHotItemsAnalysis")
    public void analysis() throws Exception {
        env.setParallelism(8);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // 从Kafka读取数据源
        DataStream<String> inputDataStream = env.addSource(
                new FlinkKafkaConsumer<>("kafka-hot-items", new SimpleStringSchema(), kafkaProperties));

        // 转换为Java Bean, 并分配时间戳和watermark
        SingleOutputStreamOperator<UserBehavior> userBehaviorDataStream = inputDataStream.map(line -> {
            String[] fields = line.split(",");
            return UserBehavior.builder()
                    .userId(Long.valueOf(fields[0]))
                    .itemId(Long.valueOf(fields[1]))
                    .categoryId(Long.valueOf(fields[2]))
                    .behavior(fields[3])
                    .timestamp(Long.valueOf(fields[4]))
                    .build();
        }).assignTimestampsAndWatermarks(new UserBehaviorAscendingTimestampExtractor());

        // 分组开窗聚合, 获取每个商品的热门度, 即每个商品的count值
        DataStream<HotItemsViewCount> windowAggregateDataStream = userBehaviorDataStream
                // 分组过滤行为出”pv“的数据
                .filter(data -> "pv".equals(data.getBehavior()))
                // 按商品ID分类
                .keyBy("itemId")
                // 打开滑窗, 间隔为1h, 步长为5min
                .timeWindow(Time.hours(1L), Time.minutes(5L))
                // 聚合操作
                .aggregate(new KafkaHotItemsCountAggregate(), new KafkaWindowHotItemsCountResult());


        // 收集同一窗口的所有商品count数据, 后排序, 输出top N
        SingleOutputStreamOperator<TopNHotItemsResult> resultDataStream = windowAggregateDataStream
                .keyBy("windowEnd")
                .process(new TopNHotItems());

        resultDataStream.addSink(new KafkaHotItemsMySqlSink());

        env.execute(KAFKA_HOT_ITEMS.getJobName());
    }

    public static class KafkaHotItemsMySqlSink extends RichSinkFunction<TopNHotItemsResult> {

        private transient Connection connection;

        private transient PreparedStatement clearStatement;

        private transient PreparedStatement selectStatement;

        private transient PreparedStatement insertStatement;

        private transient PreparedStatement updateStatement;

        private transient boolean isFirst = true;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ubas?serverTimezone=UTC", "root", "1015");
            clearStatement = connection.prepareStatement("TRUNCATE TABLE kafka_hot_items");
            selectStatement = connection.prepareStatement("SELECT 1 FROM kafka_hot_items WHERE window_end = ? LIMIT 1");
            insertStatement = connection.prepareStatement("INSERT INTO kafka_hot_items(window_end, details) VALUES(?, ?)");
            updateStatement = connection.prepareStatement("UPDATE kafka_hot_items SET details = ? WHERE window_end = ?");
        }

        @Override
        public void close() throws Exception {
            updateStatement.close();
            selectStatement.close();
            clearStatement.close();
            insertStatement.close();
            connection.close();
        }

        @Override
        public void invoke(TopNHotItemsResult value, SinkFunction.Context context) throws Exception {
            if (isFirst) {
                clearStatement.execute();
                isFirst = false;
                return;
            }

            selectStatement.setString(1, value.getWindowEnd());
            boolean next = selectStatement.executeQuery().next();

            if (next) {
                updateStatement.setString(1, JacksonUtils.obj2json(value.getDetails()));
                updateStatement.setString(2, value.getWindowEnd());
                updateStatement.execute();
            } else {
                insertStatement.setString(1, value.getWindowEnd());
                insertStatement.setString(2, JacksonUtils.obj2json(value.getDetails()));
                insertStatement.execute();
            }
        }
    }
}
